const vscode = require("vscode");
const fs = require("fs");
const path = require("path");
const { exec } = require("child_process");

function activate(context) {
  // 注册命令
  let disposable = vscode.commands.registerCommand(
    "nvmrc-switcher.switchVersion",
    () => {
      switchNodeVersion(true);
    }
  );

  context.subscriptions.push(disposable);

  // 监听文件打开事件
  vscode.workspace.onDidOpenTextDocument((document) => {
    if (path.basename(document.fileName) === ".nvmrc") {
      switchNodeVersion();
    }
  });

  // 监听活动编辑器变化事件
  vscode.window.onDidChangeActiveTextEditor((editor) => {
    if (editor && path.basename(editor.document.fileName) === ".nvmrc") {
      switchNodeVersion();
    }
  });

  // 启动时
  switchNodeVersion();
}

let isMessageBoxVisible = false;

function delayClose(msg) {
  let messagePromise = vscode.window.showInformationMessage(msg);
  // 3秒后自动关闭信息消息
  setTimeout(() => {
    // 模拟用户点击消息框的关闭按钮
    messagePromise.then(
      () => {},
      () => {}
    );
  }, 3500);
}

function switchNodeVersion(byCommand) {
  // 获取工作区根目录
  const workspaceFolders = vscode.workspace.workspaceFolders;
  if (!workspaceFolders) {
    if (byCommand) delayClose(`Workspace root is empty.`);
    return;
  }
  const rootPath = workspaceFolders[0].uri.fsPath;

  // 读取 .nvmrc 文件
  const nvmrcPath = path.join(rootPath, ".nvmrc");
  if (!fs.existsSync(nvmrcPath)) {
    if (byCommand) delayClose(`.nvmrc file not found in the workspace root.`);
    return;
  }

  const nvmrcVersion = fs.readFileSync(nvmrcPath, "utf8").trim();
  // 验证版本号格式
  const semverRegex = /^(\d+)\.(\d+)\.(\d+)$/;
  if (!semverRegex.test(nvmrcVersion)) {
    delayClose(`Invalid Node.js version in .nvmrc, please check.`);
    return;
  }

  // 获取当前 Node.js 版本
  exec("node -v", (err, stdout, stderr) => {
    if (err) {
      vscode.window.showErrorMessage(`${stderr}`);
      return;
    }

    const currentVersion = stdout.trim().replace("v", "");

    if (nvmrcVersion === currentVersion) {
      delayClose(`Node.js version is already v${currentVersion}.`);
    } else {
      if (isMessageBoxVisible) {
        return; // 如果消息框已经显示，则不再显示新的消息框
      }
      isMessageBoxVisible = true;
      vscode.window
        .showInformationMessage(
          `Detected Node.js version ${nvmrcVersion} in .nvmrc. Do you want to switch to this version?`,
          "Yes",
          "No"
        )
        .then((selection) => {
          if (selection === "Yes") {
            exec(`nvm use ${nvmrcVersion}`, (error, stdout, stderr) => {
              if (err) {
                vscode.window.showErrorMessage(`${stderr}`);
                return;
              }

              delayClose(`${stdout}`);
              isMessageBoxVisible = false; // 消息框关闭时重置标志
            });
          } else {
            isMessageBoxVisible = false; // 消息框关闭时重置标志
          }
        });
    }
  });
}

function deactivate() {}

module.exports = {
  activate,
  deactivate,
};
